# -*- mode: python -*-
###
#
# (c) 2000-2007 Wijnand Modderman <wijnand at tehmaze dot com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###

# system imports
import os
import sys

# DDB imports
from ddb.lang import lang
from ddb.log import log
from ddb.tools import syntax
from ddb.module import LoadException
from ddb.access import access
from raw.feedback import feedback

# Twisted imports
from twisted.internet import reactor

# DDB exports
EXPORT=['Modules']
ALLOW_TWISTED_REBUILD=True # better reload magic

class Modules:
    @access('n', False)
    def load(self, event):
        """<module>

        Loads the module <module>, python dotted module notation.
        
        Example: module/test.py becomes: module.test"""
        if not event.args:
            event.reply(syntax())
            return
        try:
            event.transport.modules.load(event.args)
        except LoadException, e:
            event.reply('exception: %s' % str(e))
        except ImportError, e:
            event.reply('module %s not loaded: %s' % (event.args, str(e)))
        else:
            event.reply('module %s loaded' % event.args)

    @access('n', False)
    def reload(self, event):
        """<module>

        Reloads the module <module>, python dotted module notation.
        
        Example: module/test.py becomes: module.test"""
        if not event.args:
            event.reply(syntax())
            return
        try:
            event.transport.modules.reload(event.args)
        except LoadException, e:
            event.reply('exception: %s' % str(e))
        except ImportError, e:
            event.reply('module %s not reloaded: %s' % (event.args, str(e)))
        else:
            event.reply('module %s reloaded' % event.args)

    def modules(self, event):
        cmodules = event.commands.register.keys()
        cmodules.sort()
        cmodules = ['\002%s\002' % x for x in cmodules]
        rmodules = event.transport.modules.register.keys()
        rmodules.sort()
        rmodules = ['\002%s\002' % x for x in rmodules]
        event.reply('Loaded command modules: %s, Loaded raw modules: %s' % (', '.join(cmodules), ', '.join(rmodules)))

    @access('n', False)
    def die(self, event):
        reactor.stop()
        os.kill(os.getpid(), 9)

    @access('n', False)
    def stop(self, event):
        reactor.stop()
        os.kill(os.getpid(), 15)

    @access('n', 'n')
    def reboot(self, event):
        """Reboots the bot."""
        event.reply('%s [yes/no]' % lang('are you sure'))
        feedback.wait(event, ['yes', 'no'], self._reboot, [event.user.identity], True)

    def _reboot(self, event):
        if event.message.lower() == 'yes':
            event.reply(lang('rebooting'))
            reactor.stop()
            command = sys.argv[0]
            if len(sys.argv) > 1:
                args = tuple(sys.argv[1:])
            else:
                args = tuple([])
            log.msg('Executing: %s %s' % (command, ' '.join(args)))
            os.execv(command, args)
        else:
            event.reply(lang('aborted', 'reboot'))

# vim:ts=4:sw=4:et:
